from rest_framework import serializers
from apps.users.models import User


class AdminSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'
        extra_kwargs = {
            'password': {
                'write_only': True
            }
        }

    def create(self, validated_data):
        user = super().create(validated_data)
        user.is_staff = True   #手动设置为管理员
        user.set_password(validated_data.get('password'))
        user.save()
        return user

    #更新用户密码要加密保存set_password
    def update(self, instance, validated_data):
        instance = super().update(instance,validated_data)
        if validated_data.get('password'):
            instance.set_password(validated_data.get('password'))
            instance.save()
        return instance